//
//  LYPhotoZoomView.m
//  LYPhotoBrowser
//
//  Created by LvYuan on 16/12/12.
//  Copyright © 2016年 LvYuan. All rights reserved.
//

#import "LYPhotoZoomView.h"
#import "LYPhoto.h"
#import "LYPhotoBrowserConfig.h"
#import "LYProgressView.h"
#import "UIImageView+WebCache.h"

@interface LYPhotoZoomView ()<UIScrollViewDelegate>

@property (nonatomic,strong) LYProgressView * progressView;
@property (nonatomic,strong) UITapGestureRecognizer * doubleTap;
@property (nonatomic,strong) UITapGestureRecognizer * singleTap;
@property (nonatomic, strong) UIImage * placeHolderImage;
@property (nonatomic, strong) UIButton * reloadButton;
@property (nonatomic, assign) BOOL hasLoadedImage;

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;

@end

@implementation LYPhotoZoomView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.scrollView];
        //添加单双击事件
        [self addGestureRecognizer:self.doubleTap];
        [self addGestureRecognizer:self.singleTap];
    }
    return self;
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, 0, ScreenWidth_ly, ScreenHeight_ly);
        [_scrollView addSubview:self.imageView];
        _scrollView.delegate = self;
        _scrollView.clipsToBounds = YES;
    }
    return _scrollView;
}

- (UIImageView *)imageView{
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.frame = CGRectMake(0, 0, ScreenWidth_ly, ScreenHeight_ly);
        _imageView.userInteractionEnabled = YES;
    }
    return _imageView;
}

- (UITapGestureRecognizer *)doubleTap{
    if (!_doubleTap) {
        _doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
        _doubleTap.numberOfTapsRequired = 2;
        _doubleTap.numberOfTouchesRequired  =1;
    }
    return _doubleTap;
}

- (UITapGestureRecognizer *)singleTap{
    if (!_singleTap) {
        _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        _singleTap.numberOfTapsRequired = 1;
        _singleTap.numberOfTouchesRequired = 1;
        _singleTap.delaysTouchesBegan = YES;
        //只能有一个手势存在
        [_singleTap requireGestureRecognizerToFail:self.doubleTap];
        
    }
    return _singleTap;
}

#pragma mark 双击
- (void)handleDoubleTap:(UITapGestureRecognizer *)recognizer{
    
    //图片加载完之后才能响应双击放大
    if (!self.hasLoadedImage) {
        return;
    }
    
    CGPoint touchPoint = [recognizer locationInView:self];
    
    if (self.scrollView.zoomScale <= 1.0) {
        
        CGFloat scaleX = touchPoint.x + self.scrollView.contentOffset.x;//需要放大的图片的X点
        CGFloat sacleY = touchPoint.y + self.scrollView.contentOffset.y;//需要放大的图片的Y点
        [self.scrollView zoomToRect:CGRectMake(scaleX, sacleY, 10, 10) animated:YES];
        
    } else {
        [self.scrollView setZoomScale:1.0 animated:YES]; //还原
    }
    
}
#pragma mark 单击
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer{
    if (self.tapBlock) {
        _tapBlock(recognizer);
    }
}

- (void)setProgress:(CGFloat)progress{
    _progress = progress;
    _progressView.progress = progress;
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder{
    
    _placeHolderImage = placeholder;
    
    self.progressView = [self newProgressView];
    
    _loading = YES;
    
    //加载图片
    WEAKSELF_LY;
    [_imageView sd_setImageWithURL:url placeholderImage:placeholder?placeholder:nil options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
        wself.progress = (CGFloat)receivedSize / expectedSize;
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        _loading = NO;
        _progressView.hidden = YES;
        
        if (error) {
            self.reloadButton = [self newReloadBtn];
            return;
        }
        wself.hasLoadedImage = YES;//图片加载成功
    }];
}

- (LYProgressView *)newProgressView{
    if (_progressView) {
        [_progressView removeFromSuperview];
    }
    //添加进度指示器
    LYProgressView *progressView = [[LYProgressView alloc] init];
    progressView.center = CGPointMake(ScreenWidth_ly * 0.5, ScreenHeight_ly * 0.5);
    [self addSubview:progressView];
    return progressView;
}

- (UIButton *)newReloadBtn{
    if (_reloadButton) {
        [_reloadButton removeFromSuperview];
    }
    //图片加载失败的处理，此处可以自定义各种操作（...）
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.layer.cornerRadius = 2;
    button.clipsToBounds = YES;
    button.bounds = CGRectMake(0, 0, 200, 40);
    button.center = CGPointMake(ScreenWidth_ly * 0.5, ScreenHeight_ly * 0.5);
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    button.backgroundColor = [UIColor colorWithRed:0.1f green:0.1f blue:0.1f alpha:0.3f];
    [button setTitle:@"原图加载失败，点击重新加载" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(reloadImage) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:button];
    return button;
}

- (void)setPhoto:(LYPhoto *)photo{
    _photo = photo;
    if (photo) {
        [self reloadImage];
    }
}

- (void)reloadImage{
    if (_photo) {
        NSString * picUrl = _photo.largePicUrl.length?_photo.largePicUrl:nil;
        UIImage * placeImg = _photo.thumbImage?:nil;
        if (picUrl) {
                    [self setImageWithURL:[NSURL URLWithString:picUrl] placeholderImage:placeImg];
        }
    }
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    _progressView.center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
    _scrollView.frame = self.bounds;
    _progressView.center = _scrollView.center;
    [self resetFrame];
    
}

- (void)resetFrame{
    
    CGRect frame = self.scrollView.frame;
    
    if (self.imageView.image) {
        
        CGSize imageSize = self.imageView.image.size;//获得图片的size
        CGRect imageFrame = CGRectMake(0, 0, imageSize.width, imageSize.height);
        
        if (kIsFullWidthWhenLandScape_ly) {//图片宽度始终==屏幕宽度
            
            CGFloat ratio = frame.size.width/imageFrame.size.width;
            imageFrame.size.height = imageFrame.size.height*ratio;
            imageFrame.size.width = frame.size.width;
            
        } else{
            
            if (frame.size.width<=frame.size.height) {
                //竖屏时候
                CGFloat ratio = frame.size.width/imageFrame.size.width;
                imageFrame.size.height = imageFrame.size.height*ratio;
                imageFrame.size.width = frame.size.width;
            }else{ //横屏的时候
                CGFloat ratio = frame.size.height/imageFrame.size.height;
                imageFrame.size.width = imageFrame.size.width*ratio;
                imageFrame.size.height = frame.size.height;
            }
            
        }
        
        self.imageView.frame = imageFrame;

        self.scrollView.contentSize = self.imageView.frame.size;
        self.imageView.center = [self centerOfScrollViewContent:self.scrollView];
        
        //根据图片大小找到最大缩放等级，保证最大缩放时候，不会有黑边
        CGFloat maxScale = frame.size.height/imageFrame.size.height;
        maxScale = frame.size.width/imageFrame.size.width>maxScale?frame.size.width/imageFrame.size.width:maxScale;
        //超过了设置的最大的才算数
        maxScale = maxScale>kMaxZoomScale_ly?maxScale:kMaxZoomScale_ly;
        
        //初始化
        self.scrollView.minimumZoomScale = kMinZoomScale_ly;
        self.scrollView.maximumZoomScale = maxScale;
        self.scrollView.zoomScale = 1.0f;
        
    }else{
        frame.origin = CGPointZero;
        self.imageView.frame = frame;
        //重置内容大小
        self.scrollView.contentSize = self.imageView.frame.size;
    }
    self.scrollView.contentOffset = CGPointZero;
}


#pragma mark UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    //这里是缩放进行时调整
    self.imageView.center = [self centerOfScrollViewContent:scrollView];
}

- (CGPoint)centerOfScrollViewContent:(UIScrollView *)scrollView{
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    CGPoint actualCenter = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                       scrollView.contentSize.height * 0.5 + offsetY);
    return actualCenter;
}



@end
